package com.ly.quickdev.library.fragment;

import com.ly.quickdev.library.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;

public abstract class BaseTabFragment extends DevBaseFragment {
	private FragmentTabHost mFragmentTabHost;
	private String[] mTabTitles;
	private Class<? extends Fragment>[] mFragments;

	private int[] mTabIcons;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mTabTitles = getTabTitles();
		mFragments = getFragments();
		mTabIcons = getTabIcons();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.activity_fragment_tabs, null);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		mFragmentTabHost = (FragmentTabHost) view
				.findViewById(android.R.id.tabhost);

		mFragmentTabHost.setup(getActivity(), getChildFragmentManager(),
				android.R.id.tabcontent);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		int size = mTabTitles.length;
		for (int i = 0; i < size; i++) {
			TabSpec tab = mFragmentTabHost.newTabSpec(mTabTitles[i]);
			tab.setIndicator(getIndicatorView(i));
			mFragmentTabHost
					.addTab(tab, mFragments[i], getFragmentArguments(i));
		}
	}

	public boolean useDefaultIndicatorView() {
		return true;
	}

	public abstract String[] getTabTitles();

	public abstract Class<? extends Fragment>[] getFragments();

	public abstract Bundle getFragmentArguments(int position);

	public View getIndicatorView(int position) {
		final View v = getActivity().getLayoutInflater().inflate(
				R.layout.tab_indicator, null);
		final TextView tv = (TextView) v.findViewById(R.id.title);
		final ImageView iv = (ImageView) v.findViewById(R.id.icon);
		tv.setText(mTabTitles[position]);
		iv.setImageResource(mTabIcons[position]);
		return v;
	}

	public abstract int[] getTabIcons();
}
